package com.example.shushiyunsst.fragment.main.home.child.icon_sst

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.shushiyunsst.R
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import org.greenrobot.eventbus.EventBus

class IconTransferSettingFragment : BaseFragmentEx() {

    companion object {
        fun newInstance(transferType: Int, icon: Int): IconTransferSettingFragment {
            val args = Bundle()
            args.putInt("transferType", transferType)
            args.putInt("icon", icon)
            val fragment = IconTransferSettingFragment()
            fragment.arguments = args
            return fragment
        }


    }

    private var transferType: Int = ICON_TRANSFER_SETTING_SELL

    private var icon = TOKEN_TYPE_SST

    private lateinit var lestTitle: TextView

    private lateinit var almostTitle: TextView

    private lateinit var buyTitle: TextView

    private lateinit var title: TextView

    private lateinit var iconTypeLest: TextView

    private lateinit var iconTypeAlmost: TextView

    private lateinit var iconTypeStore: TextView

    private lateinit var store: EditText

    private lateinit var lest: EditText

    private lateinit var almost: EditText

    private lateinit var buy: EditText

    private lateinit var moneyTv: TextView

    private lateinit var storeTitle: TextView

    private lateinit var title_template: TextView

    private lateinit var mPriceUnit: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        transferType = arguments?.getInt("transferType", transferType) ?: transferType
        icon = arguments?.getInt("icon", icon) ?: icon
    }

    override fun getLayoutId(): Any {
        return R.layout.icon_sst_transfer_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = "买卖设置"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        mPriceUnit = view.findViewById(R.id.mPriceUnit)

        title_template = view.findViewById(R.id.title_template)

        iconTypeLest = view.findViewById(R.id.iconTypeLest)
        iconTypeAlmost = view.findViewById(R.id.iconTypeAlmost)
        iconTypeStore = view.findViewById(R.id.iconTypeStore)

        moneyTv = view.findViewById(R.id.moneyTv)
        storeTitle = view.findViewById(R.id.storeTitle)
        store = view.findViewById(R.id.store)
        title = view.findViewById(R.id.title)
        lestTitle = view.findViewById(R.id.lestTitle)
        almostTitle = view.findViewById(R.id.almostTitle)
        buyTitle = view.findViewById(R.id.buyTitle)

        lest = view.findViewById(R.id.lest)
        almost = view.findViewById(R.id.almost)
        buy = view.findViewById(R.id.buy)

        showTitleByTransferType()


        showTitleByIcon()


        view.findViewById<View>(R.id.settingBtn).setOnClickListener {
            if (checkInfo())
                when (icon) {
                    TOKEN_TYPE_SST -> {
                        onSSTSetting()
                    }
                    TOKEN_TYPE_CML -> {
                        onCMLSetting()
                    }
                }

        }
    }


    @SuppressLint("SetTextI18n")
    private fun showTitleByIcon() {
        when (icon) {
            TOKEN_TYPE_SST -> {
                val walletSst = R.string.wallet_sst

                title_template.text = "当前SST余额"

                val sst = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()?.totalBalance

                moneyTv.text = sst.toString()

                iconTypeLest.setText(walletSst)

                iconTypeAlmost.setText(walletSst)

                iconTypeStore.setText(walletSst)

                mPriceUnit.setText(R.string.wallet_cny)

                val manager = PriceSetting.manager
                val hint =
                    if (transferType == ICON_TRANSFER_SETTING_BUY) manager.pubTxBuyPrice else manager.pubTxSellPrice

                buy.hint = hint
            }
            TOKEN_TYPE_CML -> {

                var walletIcon = 0

                var walletIconStr = ""

                val balanceInfo =
                    BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()?.balanceInfo

                var titleTemplate = ""

                var mBalance = ""

                when (transferType) {
                    ICON_TRANSFER_SETTING_SELL -> {

                        walletIcon = R.string.wallet_sst

                        walletIconStr =_mActivity.getString(walletIcon)

                        titleTemplate = "当前${walletIconStr}余额"

                        mBalance = balanceInfo?.sstBalance.toString()
                    }
                    ICON_TRANSFER_SETTING_BUY -> {

                        walletIcon = R.string.wallet_cml

                        walletIconStr =_mActivity.getString(walletIcon)

                        mBalance = balanceInfo?.scmlBalance.toString()

                        titleTemplate = "当前母币${walletIconStr}余额"
                    }
                }

                title_template.text = titleTemplate

                moneyTv.text = mBalance

                iconTypeLest.setText(R.string.wallet_cml)

                iconTypeAlmost.setText(R.string.wallet_cml)

                iconTypeStore.setText(R.string.wallet_cml)

                mPriceUnit.setText(R.string.wallet_sst)
            }
        }
    }

    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        if (msg?.message == TO_REFRESH_BALANCE_INFO) {
            showTitleByIcon()
        }
    }

    private fun showTitleByTransferType() {
        when(transferType){
            ICON_TRANSFER_SETTING_SELL->{
                title.text ="卖出设置"

                lestTitle.text="单笔卖出设置最少数量"

                almostTitle.text ="单笔卖出设置最多数量"

                buyTitle.text ="卖出价格"
            }
            ICON_TRANSFER_SETTING_BUY->{
                title.text ="买入设置"

                lestTitle.text="单笔买入设置最少数量"

                almostTitle.text ="单笔买入设置最多数量"

                buyTitle.text ="买入价格"
            }
        }
//        title.text =
//            if (transferType == ICON_TRANSFER_SETTING_SELL)
//                "卖出设置" else "买入设置"
//
//        lestTitle.text =
//            if (transferType == ICON_TRANSFER_SETTING_SELL)
//                "单笔卖出设置最少数量" else "单笔买入设置最少数量"
//
//        almostTitle.text =
//            if (transferType == ICON_TRANSFER_SETTING_SELL)
//                "单笔卖出设置最多数量" else "单笔买入设置最多数量"
//
//        buyTitle.text =
//            if (transferType == ICON_TRANSFER_SETTING_SELL)
//                "卖出价格" else "买入价格"
    }

    private fun checkInfo(): Boolean {
        var flag = true

        val limitMax = almost.text.toString()
        val limitMin = lest.text.toString()
        val price = buy.text.toString()
        val stock = store.text.toString()

        if (limitMax.isEmpty()) {
            Toast.makeText(_mActivity, "请输入${almostTitle.text}", Toast.LENGTH_SHORT).show()
            flag = false
        }

        if (limitMin.isEmpty()) {
            Toast.makeText(_mActivity, "请输入${lestTitle.text}", Toast.LENGTH_SHORT).show()
            flag = false
        }

        if (price.isEmpty()) {
            Toast.makeText(_mActivity, "请输入${buyTitle.text}", Toast.LENGTH_SHORT).show()
            flag = false
        }

        if (stock.isEmpty()) {
            Toast.makeText(_mActivity, "请输入${storeTitle.text}", Toast.LENGTH_SHORT).show()
            flag = false
        }


        return flag

    }

    private fun onCMLSetting() {
        val limitMax = almost.text.toString()
        val limitMin = lest.text.toString()
        val price = buy.text.toString()
        val stock = store.text.toString()

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val tokenType = when (icon) {
            TOKEN_TYPE_SST -> _mActivity.getString(R.string.wallet_sst)
            TOKEN_TYPE_CML -> _mActivity.getString(R.string.wallet_cml)
            else -> ""
        }

        val map = mapOf(
            "limitMax" to limitMax,
            "limitMin" to limitMin,
            "price" to price,
            "stock" to stock,
            "tokenType" to tokenType,
            "txType" to transferType,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.saveScmlTx)
            .success {
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }
            .failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    private fun onSSTSetting() {
        val limitMax = almost.text.toString()
        val limitMin = lest.text.toString()
        val price = buy.text.toString()
        val stock = store.text.toString()

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val tokenType = when (icon) {
            TOKEN_TYPE_SST -> _mActivity.getString(R.string.wallet_sst)
            TOKEN_TYPE_CML -> _mActivity.getString(R.string.wallet_cml)
            else -> ""
        }

        val map = mapOf(
            "limitMax" to limitMax,
            "limitMin" to limitMin,
            "price" to price,
            "stock" to stock,
            "tokenType" to tokenType,
            "txType" to transferType,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.saveTokenTx)
            .success {
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }
            .error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()
            }.build().post()
    }
}